package com.pureut.equipment.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pureut.equipment.domain.InspectionItemPlan;
import com.pureut.equipment.domain.MaintenancePlan;
import com.pureut.equipment.domain.PatrolItemPlan;
import com.pureut.equipment.domain.PlannedAllocation;
import com.pureut.equipment.domain.vo.InspectionWorkOrderVo;
import com.pureut.equipment.domain.vo.MaintenanceWorkOrderVo;
import com.pureut.equipment.domain.vo.PatrolWorkOrderVo;
import com.pureut.equipment.mapper.InspectionItemPlanMapper;
import com.pureut.equipment.mapper.MaintenancePlanMapper;
import com.pureut.equipment.mapper.PatrolItemPlanMapper;
import com.pureut.equipment.mapper.PlannedAllocationMapper;
import com.pureut.equipment.service.InspectionItemPlanService;
import com.pureut.equipment.service.InspectionWorkOrderService;
import com.pureut.equipment.service.MaintenanceWorkOrderService;
import com.pureut.equipment.service.PatrolWorkOrderService;
import com.pureut.equipment.util.TimeUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 定时任务控制层
 */
@RestController
@RequestMapping("/schedulignTask")
public class SchedulingTaskController {

    /**
     * 保养计划mapper
     */
    @Resource
    MaintenancePlanMapper maintenancePlanMapper;

    /**
     * 计划配置mapper
     */
    @Resource
    PlannedAllocationMapper plannedAllocationMapper;

    /**
     * 保养工单service
     */
    @Resource
    MaintenanceWorkOrderService maintenanceWorkOrderService;

    /**
     * 点检计划mapper
     */
    @Resource
    InspectionItemPlanMapper inspectionItemPlanMapper;

    /**
     * 点检计划service
     */
    @Resource
    InspectionItemPlanService inspectionItemPlanService;

    /**
     * 点检工单service
     */
    @Resource
    InspectionWorkOrderService inspectionWorkOrderService;

    /**
     * 巡检计划mapper
     */
    @Resource
    PatrolItemPlanMapper patrolItemPlanMapper;

    /**
     * 巡检计划service
     */
    @Resource
    PatrolWorkOrderService patrolWorkOrderService;


    /**
     * 触发生成工单
     */
    @PostMapping("/generatingWorkOrder")
    public void generationWorkOrder() throws Exception {
        //获取启用的保养计划
        List<MaintenancePlan> maintenancePlans = maintenancePlanMapper.selectList(new QueryWrapper<MaintenancePlan>().lambda().eq(MaintenancePlan::getStatus, 1));
        for (MaintenancePlan entity : maintenancePlans) {
            //获取对应的计划配置信息
            PlannedAllocation plannedAllocation = plannedAllocationMapper.selectOne(new QueryWrapper<PlannedAllocation>().lambda().eq(PlannedAllocation::getPlanId, entity.getId()).eq(PlannedAllocation::getAllocationType, 1));
            //如果该计划是日
            if (plannedAllocation.getPlanType() == 1) {
                //获取执行周期
                int executionInterval = plannedAllocation.getExecutionInterval();
                //判断当前时间与计划开始时间相差天数是否达到执行周期
                int differDays = TimeUtils.getDifferDays(entity.getPlanStartTime(), new Date());
                //判断当前时间是否在计划开始时间和计划结束时间之内
                boolean effectiveDate = TimeUtils.isEffectiveDate(new Date(), entity.getPlanStartTime(), entity.getPlanEndTime());
                if (differDays % executionInterval == 0 && effectiveDate) {
                    //如果可以整除，就生成对应的保养工单
                    MaintenanceWorkOrderVo maintenanceWorkOrderVo = new MaintenanceWorkOrderVo();
                    maintenanceWorkOrderVo.setMaintenanceProjectIdStr(entity.getMaintenanceProjectIdStr());
                    maintenanceWorkOrderVo.setSubordinatePlan(entity.getId());
                    maintenanceWorkOrderVo.setDeviceIds(entity.getEquipmentIdStr());
                    maintenanceWorkOrderService.addScheduling(maintenanceWorkOrderVo);
                }
            }
            //如果是周
            if (plannedAllocation.getPlanType() == 2) {
                //获取执行周期
                int executionInterval = plannedAllocation.getExecutionInterval();
                Date date = new Date();
                Date planStartTime = entity.getPlanStartTime();
                int i1 = TimeUtils.calcWeekOffset(planStartTime, date);
                //如果当前时间所属的周减去计划开始时间所属的周的差值和执行周期取模为整，并且当前时间所在的日期，在开始时间和结束时间之内
                boolean effectiveDate = TimeUtils.isEffectiveDate(new Date(), entity.getPlanStartTime(), entity.getPlanEndTime());

                if (i1 % executionInterval == 0 && effectiveDate) {
                    //获取每周执行的字符串时间
                    List<String> executionCycle = Arrays.asList(plannedAllocation.getExecutionCycle().split(","));
                    //获取当前时间是星期几
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String i = String.valueOf(TimeUtils.dayForWeek(simpleDateFormat.format(new Date())));
                    //如果当前星期几包含在周执行天数
                    if (executionCycle.contains(i)) {
                        //如果可以整除，就生成对应的保养工单
                        MaintenanceWorkOrderVo maintenanceWorkOrderVo = new MaintenanceWorkOrderVo();
                        maintenanceWorkOrderVo.setMaintenanceProjectIdStr(entity.getMaintenanceProjectIdStr());
                        maintenanceWorkOrderVo.setDeviceIds(entity.getEquipmentIdStr());
                        maintenanceWorkOrderVo.setSubordinatePlan(entity.getId());
                        maintenanceWorkOrderService.addScheduling(maintenanceWorkOrderVo);
                    }
                }
            }
            //如果是月
            if (plannedAllocation.getPlanType() == 3) {
                List<String> monthList = Arrays.asList(plannedAllocation.getExecutionMonth().split(","));
                List<String> dayList = Arrays.asList(plannedAllocation.getExecutionDays().split(","));
                StringBuilder stringBuilder = new StringBuilder();
                for (String entityMonth : monthList) {
                    for (String entityDay : dayList) {
                        stringBuilder.append(entityMonth).append("-").append(entityDay).append(",");
                    }
                }
                StringBuilder dateResult = stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                //获取当前时间
                SimpleDateFormat sf = new SimpleDateFormat("MM-dd");
                String format = sf.format(new Date());
                //判断当前时间是否在计划开始时间和计划结束时间之内
                boolean effectiveDate = TimeUtils.isEffectiveDate(new Date(), entity.getPlanStartTime(), entity.getPlanEndTime());
                if (format.contains(dateResult) && effectiveDate) {
                    MaintenanceWorkOrderVo maintenanceWorkOrderVo = new MaintenanceWorkOrderVo();
                    maintenanceWorkOrderVo.setMaintenanceProjectIdStr(entity.getMaintenanceProjectIdStr());
                    maintenanceWorkOrderVo.setDeviceIds(entity.getEquipmentIdStr());
                    maintenanceWorkOrderVo.setSubordinatePlan(entity.getId());
                    maintenanceWorkOrderService.addScheduling(maintenanceWorkOrderVo);
                }
            }
        }

        //获取启用的点检计划
        List<InspectionItemPlan> inspectionItemPlans = inspectionItemPlanMapper.selectList(new QueryWrapper<InspectionItemPlan>().lambda().eq(InspectionItemPlan::getStatus, 1));
        for (InspectionItemPlan entity : inspectionItemPlans) {
            //获取对应的计划配置信息
            PlannedAllocation plannedAllocation = plannedAllocationMapper.selectOne(new QueryWrapper<PlannedAllocation>().lambda().eq(PlannedAllocation::getPlanId, entity.getId()).eq(PlannedAllocation::getAllocationType, 2));
            //如果该计划是日
            if (plannedAllocation.getPlanType() == 1) {
                //获取执行周期
                int executionInterval = plannedAllocation.getExecutionInterval();
                //判断当前时间与计划开始时间相差天数是否达到执行周期
                int differDays = TimeUtils.getDifferDays(entity.getPlanStartTime(), new Date());
                //判断当前时间是否在计划开始时间和计划结束时间之内
                boolean effectiveDate = TimeUtils.isEffectiveDate(new Date(), entity.getPlanStartTime(), entity.getPlanEndTime());
                if (differDays % executionInterval == 0 && effectiveDate) {
                    //如果可以整除，就生成对应的点检工单
                    InspectionWorkOrderVo inspectionWorkOrderVo = new InspectionWorkOrderVo();
                    inspectionWorkOrderVo.setInspectionItemIdStr(entity.getInspectionItemIdStr());
                    inspectionWorkOrderVo.setDeviceIds(entity.getEquipmentIdStr());
                    inspectionWorkOrderVo.setSubordinatePlan(entity.getId());
                    inspectionWorkOrderService.schedulingAdd(inspectionWorkOrderVo);
                }
            }
            //如果是周
            if (plannedAllocation.getPlanType() == 2) {
                //获取执行周期
                int executionInterval = plannedAllocation.getExecutionInterval();
                Date date = new Date();
                Date planStartTime = entity.getPlanStartTime();
                int i1 = TimeUtils.calcWeekOffset(planStartTime, date);
                //如果当前时间所属的周减去计划开始时间所属的周的差值和执行周期取模为整，并且当前时间所在的日期，在开始时间和结束时间之内
                boolean effectiveDate = TimeUtils.isEffectiveDate(new Date(), entity.getPlanStartTime(), entity.getPlanEndTime());

                if (i1 % executionInterval == 0 && effectiveDate) {
                    //获取每周执行的字符串时间
                    List<String> executionCycle = Arrays.asList(plannedAllocation.getExecutionCycle().split(","));
                    //获取当前时间是星期几
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String i = String.valueOf(TimeUtils.dayForWeek(simpleDateFormat.format(new Date())));
                    //如果当前星期几包含在周执行天数
                    if (executionCycle.contains(i)) {
                        //如果可以整除，就生成对应的保养工单
                        InspectionWorkOrderVo inspectionWorkOrderVo = new InspectionWorkOrderVo();
                        inspectionWorkOrderVo.setInspectionItemIdStr(entity.getInspectionItemIdStr());
                        inspectionWorkOrderVo.setDeviceIds(entity.getEquipmentIdStr());
                        inspectionWorkOrderVo.setSubordinatePlan(entity.getId());
                        inspectionWorkOrderService.schedulingAdd(inspectionWorkOrderVo);
                    }
                }
            }
            //如果是月
            if (plannedAllocation.getPlanType() == 3) {
                List<String> monthList = Arrays.asList(plannedAllocation.getExecutionMonth().split(","));
                List<String> dayList = Arrays.asList(plannedAllocation.getExecutionDays().split(","));
                StringBuilder stringBuilder = new StringBuilder();
                for (String entityMonth : monthList) {
                    for (String entityDay : dayList) {
                        stringBuilder.append(entityMonth).append("-").append(entityDay).append(",");
                    }
                }
                StringBuilder dateResult = stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                //获取当前时间
                SimpleDateFormat sf = new SimpleDateFormat("MM-dd");
                String format = sf.format(new Date());
                //判断当前时间是否在计划开始时间和计划结束时间之内
                boolean effectiveDate = TimeUtils.isEffectiveDate(new Date(), entity.getPlanStartTime(), entity.getPlanEndTime());
                if (format.contains(dateResult) && effectiveDate) {
                    InspectionWorkOrderVo inspectionWorkOrderVo = new InspectionWorkOrderVo();
                    inspectionWorkOrderVo.setInspectionItemIdStr(entity.getInspectionItemIdStr());
                    inspectionWorkOrderVo.setDeviceIds(entity.getEquipmentIdStr());
                    inspectionWorkOrderVo.setSubordinatePlan(entity.getId());
                    inspectionWorkOrderService.schedulingAdd(inspectionWorkOrderVo);
                }
            }
        }

        //获取启用的巡检计划
        List<PatrolItemPlan> patrolItemPlans = patrolItemPlanMapper.selectList(new QueryWrapper<PatrolItemPlan>().lambda().eq(PatrolItemPlan::getStatus, 1));
        for (PatrolItemPlan entity : patrolItemPlans) {
            //获取对应的计划配置信息
            PlannedAllocation plannedAllocation = plannedAllocationMapper.selectOne(new QueryWrapper<PlannedAllocation>().lambda().eq(PlannedAllocation::getPlanId, entity.getId()).eq(PlannedAllocation::getAllocationType, 3));
            //如果该计划是日
            if (plannedAllocation.getPlanType() == 1) {
                //获取执行周期
                int executionInterval = plannedAllocation.getExecutionInterval();
                //判断当前时间与计划开始时间相差天数是否达到执行周期
                int differDays = TimeUtils.getDifferDays(entity.getPlanStartTime(), new Date());
                //判断当前时间是否在计划开始时间和计划结束时间之内
                boolean effectiveDate = TimeUtils.isEffectiveDate(new Date(), entity.getPlanStartTime(), entity.getPlanEndTime());
                if (differDays % executionInterval == 0 && effectiveDate) {
                    //如果可以整除，就生成对应的巡检工单
                    PatrolWorkOrderVo patrolWorkOrderVo = new PatrolWorkOrderVo();
                    patrolWorkOrderVo.setPatrolItemIdStr(entity.getPatrolItemIdStr());
                    patrolWorkOrderVo.setDeviceIds(entity.getEquipmentIdStr());
                    patrolWorkOrderVo.setSubordinatePlan(entity.getId());
                    patrolWorkOrderService.addScheduling(patrolWorkOrderVo);
                }
            }
            //如果是周
            if (plannedAllocation.getPlanType() == 2) {
                //获取执行周期
                int executionInterval = plannedAllocation.getExecutionInterval();
                Date date = new Date();
                Date planStartTime = entity.getPlanStartTime();
                int i1 = TimeUtils.calcWeekOffset(planStartTime, date);
                //如果当前时间所属的周减去计划开始时间所属的周的差值和执行周期取模为整，并且当前时间所在的日期，在开始时间和结束时间之内
                boolean effectiveDate = TimeUtils.isEffectiveDate(new Date(), entity.getPlanStartTime(), entity.getPlanEndTime());
                if (i1 % executionInterval == 0 && effectiveDate) {
                    //获取每周执行的字符串时间
                    List<String> executionCycle = Arrays.asList(plannedAllocation.getExecutionCycle().split(","));
                    //获取当前时间是星期几
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String i = String.valueOf(TimeUtils.dayForWeek(simpleDateFormat.format(new Date())));
                    //如果当前星期几包含在周执行天数
                    if (executionCycle.contains(i)) {
                        //如果可以整除，就生成对应的保养工单
                        PatrolWorkOrderVo patrolWorkOrderVo = new PatrolWorkOrderVo();
                        patrolWorkOrderVo.setPatrolItemIdStr(entity.getPatrolItemIdStr());
                        patrolWorkOrderVo.setDeviceIds(entity.getEquipmentIdStr());
                        patrolWorkOrderVo.setSubordinatePlan(entity.getId());
                        patrolWorkOrderService.addScheduling(patrolWorkOrderVo);
                    }
                }
            }
            //如果是月
            if (plannedAllocation.getPlanType() == 3) {
                List<String> monthList = Arrays.asList(plannedAllocation.getExecutionMonth().split(","));
                List<String> dayList = Arrays.asList(plannedAllocation.getExecutionDays().split(","));
                StringBuilder stringBuilder = new StringBuilder();
                for (String entityMonth : monthList) {
                    for (String entityDay : dayList) {
                        stringBuilder.append(entityMonth).append("-").append(entityDay).append(",");
                    }
                }
                StringBuilder dateResult = stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                //获取当前时间
                SimpleDateFormat sf = new SimpleDateFormat("MM-dd");
                String format = sf.format(new Date());
                //判断当前时间是否在计划开始时间和计划结束时间之内
                boolean effectiveDate = TimeUtils.isEffectiveDate(new Date(), entity.getPlanStartTime(), entity.getPlanEndTime());
                if (format.contains(dateResult) && effectiveDate) {
                    PatrolWorkOrderVo patrolWorkOrderVo = new PatrolWorkOrderVo();
                    patrolWorkOrderVo.setPatrolItemIdStr(entity.getPatrolItemIdStr());
                    patrolWorkOrderVo.setDeviceIds(entity.getEquipmentIdStr());
                    patrolWorkOrderVo.setSubordinatePlan(entity.getId());
                    patrolWorkOrderService.addScheduling(patrolWorkOrderVo);
                }
            }
        }
    }
}
